﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Reflection;

namespace nsWeldController
{
    public partial class DockSerialProtocol : DockContent
    {
        public DockSerialProtocol()
        {
            InitializeComponent();
        }

        public SerialProtocol mSerialP = new SerialProtocol();
        private CLog mLog = CWeldController.mLog;
        private Queue<ET_GPES_SENDMSG> mQueueSend = new Queue<ET_GPES_SENDMSG>();

        private void DockSerialProtocol_Load(object sender, EventArgs e)
        {
            // 初始化下拉串口名称列表框
            string[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            comboBoxPortName.Items.AddRange(ports);
            comboBoxPortName.SelectedIndex = comboBoxPortName.Items.Count > 0 ? 0 : -1;
            comboBoxBaudrate.SelectedIndex = comboBoxBaudrate.Items.IndexOf("115200");
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            AbordQueryThread();
            AbordSendThread();
        }

        private void btnSerialConnect_Click(object sender, EventArgs e)
        {
            if (mSerialP.IsOpen())
            {
                mSerialP.CloseSerialCom();
            }
            else
            {
                mSerialP.OpenSerialCom(comboBoxPortName.Text, int.Parse(comboBoxBaudrate.Text));
            }

            if (mSerialP.IsOpen())
            {
                BeginSendThread();
                BeginQueryThread();
                btnSerialConnect.Text = "关闭";
                CWeldController.mDockCommandBtn.Show();
            }
            else
            {
                AbordSendThread();
                AbordQueryThread();
                btnSerialConnect.Text = "打开";
            }
        }

        #region 发送队列数据线程
        private Thread mSendThread;
        private bool bKeepSend = true;
        private void SendMessageFromQueue()
        {
            while (bKeepSend && mSerialP.IsOpen())
            {
                if (mQueueSend.Count == 0)
                {
                    Thread.Sleep(100);
                    continue;
                }

                bKeepSend = false;

                ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
                DeQueueSend(ref stSend);
                try
                {
                    ET_GPES_RECVMSG stRecv = new ET_GPES_RECVMSG();
                    byte byteR = mSerialP.EA_GP_ucTransMsg(stSend, ref stRecv, 2000);
                    if (byteR != 0)
                    {
                        mLog.LogDebug("发送命令失败，错误代码：0x" + byteR.ToString("X2") + "\n");
                    }
                    else
                    {
                        //mLog.LogMessage("发送指令成功\n");
                        // 以下处理收到的信息
                        HandleRecvMsg(stSend.CLA, stSend.INS, stRecv.RES, stRecv.recvMsg);
                    }
                }
                catch (System.Exception ex)
                {
                    mLog.LogDebug("发送查询命令失败：" + ex.Message + "\n");
                }
                finally
                {
                    bKeepSend = true;
                }
                Thread.Sleep(100);
            }
        }

        /// <summary>
        /// 获取枚举类型指定值的描述信息
        /// </summary>
        /// <typeparam name="Ttype"></typeparam>
        /// <param name="Enumtype"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public string GetEnumDesc<Ttype>(Ttype Enumtype, int index)
        {
            if (Enumtype == null || !Enumtype.GetType().IsEnum)
            {
                return "";
            }

            FieldInfo[] fieldinfo = Enumtype.GetType().GetFields();
            foreach (FieldInfo item in fieldinfo)
            {
                if (item.Name == ((INS)index).ToString())
                {
                    Object[] obj = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (obj != null && obj.Length != 0)
                    {
                        DescriptionAttribute des = (DescriptionAttribute)obj[0];
                        return des.Description;
                    }
                }
            }
            
            return "";
        }

        private void HandleRecvMsg(byte cla, byte ins, byte res, byte[] recvMsg)
        {
            // 用于显示控制指令的发送成功状态
            if (cla != (byte)CLA.CLA_QUERY)
            {
                if (res == 0)
                {
                    mLog.LogMessage("发送{0}指令成功\n", GetEnumDesc(new INS(), ((INS)ins).GetHashCode()));
                } 
                else
                {
                    mLog.LogWarning("执行{0}指令失败\n", GetEnumDesc(new INS(), ((INS)ins).GetHashCode()));
                }
            }

            // res不等于0，recvMsg为返回的错误信息字符串
            if (res != 0)
            {
                ShowExceptionAndMessage(recvMsg);
                return;
            }
            else
            {
                if (recvMsg.Length != Marshal.SizeOf(typeof(MASHINE_INFO)))
                {
                    mLog.LogError("查询到的串口数据长度有误：期望" + Marshal.SizeOf(typeof(MASHINE_INFO)).ToString()
                        + " 实际：" + recvMsg.Length.ToString() + "\n");
                    return;
                }
                CWeldController.mMashineInfo = (MASHINE_INFO)CWeldController.BytesToStuct(recvMsg, typeof(MASHINE_INFO));

                // 更新数据到窗体
                this.Invoke(new MethodInvoker(() => CWeldController.mDockMain.ShowMashineInfo()));
            }
        }

        private void ShowExceptionAndMessage(byte[] recvMsg)
        {
            if (recvMsg[0] != 1 && recvMsg[0] != 2)
            {
                mLog.LogError("接受到的错误消息格式有误!\n");
                return;
            }
            byte[] recvMsg1 = new byte[recvMsg.Length - 1];
            Buffer.BlockCopy(recvMsg, 1, recvMsg1, 0, recvMsg1.Length);
            string msgGet = Encoding.Default.GetString(recvMsg1);
            if (recvMsg[0] == 1)
            {
                mLog.LogError(msgGet + "\n");
            }
            else if (recvMsg[0] == 2)
            {
                mLog.LogWarning(msgGet + "\n");
            }
        }

        private void BeginSendThread()
        {
            mSendThread = new Thread(SendMessageFromQueue);
            bKeepSend = true;
            mSendThread.Start();
        }

        private void AbordSendThread()
        {
            bKeepSend = false;
            if (mSendThread != null)
            {
                mSendThread.Abort();
            }
        }
        #endregion

        #region 查询状态线程
        private Thread mQueryThread;
        private bool bKeepQuery = true;

        private void QueryStatus()
        {
            while (bKeepQuery && mSerialP.IsOpen())
            {
                Thread.Sleep(500);
                if (bKeepSend == false) // 如果正在发送数据，就不插入查询指令
                {
                    continue;
                }
                ET_GPES_SENDMSG stSend = new ET_GPES_SENDMSG();
                stSend.CLA = (byte)CLA.CLA_QUERY;
                stSend.INS = 0x01;
                stSend.sendMsg = new byte[1] { 0 };
                // 如果队列中包含查询指令则不再新加
                if (mQueueSend.Contains(stSend))
                {
                    continue;
                }
                EnQueueSend(stSend);
            }
        }

        public void BeginQueryThread()
        {
            mQueryThread = new Thread(QueryStatus);
            bKeepQuery = true;
            mQueryThread.Start();
        }

        public void AbordQueryThread()
        {
            bKeepQuery = false;
            if (mQueryThread != null)
            {
                mQueryThread.Abort();
            }
        }
        #endregion

        #region 队列插入删除操作
        public bool EnQueueSend(ET_GPES_SENDMSG stSend)
        {
            if (!mSerialP.IsOpen())
            {
                mLog.LogMessage("请先连接串口\n");
                return false;
            }

            // 自动控制过程中无法发送单项控制指令,也不允许设置允许参数
            if (stSend.CLA == (byte)CLA.CLA_CTRL && stSend.INS < (byte)INS.CMD_START
                && CWeldController.mMashineInfo.iRunningFlag == 1)
            {
                mLog.LogMessage("自动运行过程中，无法发送该指令。\n");
                return false;
            }

            lock (mQueueSend)
            {
                mQueueSend.Enqueue(stSend);
            }
            
            return true;
        }

        public bool DeQueueSend(ref ET_GPES_SENDMSG stSend)
        {
            if (mQueueSend.Count == 0)
            {
                return false;
            }

            lock (mQueueSend)
            {
                stSend = mQueueSend.Dequeue();
            }
            
            return true;
        }
        #endregion

    }
}
